package com.qzsoft.zhjd.upload.service.impl;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.qzsoft.zhjd.common.enums.BizCode;
import com.qzsoft.zhjd.common.utils.RenExceptionUtils;
import com.qzsoft.zhjd.upload.service.UploadService;


/**
 * @ClassName UploadServiceImpl
 * @Description 文件上传业务接口实现
 * @author linhuawei
 * @since 2021-10-29
 */
@Service
public class UploadServiceImpl implements UploadService {

    @Value("${zhjd.upload.localhostAddr}")
    private String localhostAddr;

    @Value("${zhjd.upload.path}")
    private String uploadPath;

    @Value("${zhjd.upload.allowImage}")
    private String allowImage;

    @Override
    public String upload(MultipartFile file, String type) {
        // 判断文件类型是否存在
        if (null == type) {
            RenExceptionUtils.throwEx(BizCode.PARAMS_ERROR, "未知的文件分类");
        }

        // 判断文件是否存在
        if (null == file || file.isEmpty()) {
            RenExceptionUtils.throwEx(BizCode.PARAMS_ERROR, "附件不可为空");
        }

        // 后期文件后缀
        String filename = file.getOriginalFilename();
        int index = filename.lastIndexOf(".");
        if (-1 == index) {
            RenExceptionUtils.throwEx(BizCode.PARAMS_ERROR, "未知的文件后缀");
        }
        String suffix = filename.substring(index).toLowerCase();

        // 判断是否允许的文件类型
        if ("image".equals(type)) {
            if (!allowImage.contains(suffix)) {
                RenExceptionUtils.throwEx(BizCode.PARAMS_ERROR, "请上传[" + allowImage + "]类型的文件");
            }
        } else {
            RenExceptionUtils.throwEx(BizCode.PARAMS_ERROR, "未知的文件分类");
        }

        // 获取文件保存相对路径
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String path = "/upload/" + type + "/" + sdf.format(new Date()) + "/" + UUID.randomUUID().toString() + suffix;
        File targetFile = new File(uploadPath + path);
        if (!targetFile.getParentFile().exists()) {
            targetFile.getParentFile().mkdirs();
        }

        // 保存文件
        try {
            file.transferTo(targetFile);
        } catch (IOException e) {
            RenExceptionUtils.throwEx(BizCode.ERROR, "文件上传异常");
        }

        // 返回文件路径
        return localhostAddr + path;
    }

}
